package com.example.pokemon_chat_room.adapter;

import static android.content.Context.MODE_PRIVATE;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.example.pokemon_chat_room.MainActivity;
import com.example.pokemon_chat_room.R;
import com.example.pokemon_chat_room.pojo.AvatarBase;
import com.example.pokemon_chat_room.pojo.MyPokemonDto;
import com.example.pokemon_chat_room.request.OkHttp;
import com.example.pokemon_chat_room.ui.notifications.NotificationsFragment;
import com.example.pokemon_chat_room.util.MyImageView;

import java.io.IOException;
import java.util.List;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MyPokemonAdapter extends RecyclerView.Adapter<MyPokemonAdapter.ViewHolder> {

    public static final String ACTION_RECEIVE_MESSAGE = "com.example.pokemon_chat_room.AVATAR";
    public static final String KEY_RECEIVED_DATA = "free";

    private Dialog addTradeDialog;

    private List<MyPokemonDto> myPokemonList;
    private View view;
    private Context context;

    public MyPokemonAdapter(Context context, List<MyPokemonDto> myPokemonList) {
        this.context = context;
        this.myPokemonList = myPokemonList;
    }
    public static class ViewHolder extends RecyclerView.ViewHolder {
        private MyImageView pokemon_img;
        private TextView pokemon_txt;
        private ImageView pokemon_sex;
        private FrameLayout pokemon_info;
        public ViewHolder(View view) {
            super(view);
            // Define click listener for the ViewHolder's View

            pokemon_img = view.findViewById(R.id.pokemon_img);
            pokemon_txt = view.findViewById(R.id.pokemon_txt);
            pokemon_sex = view.findViewById(R.id.pokemon_sex);
            pokemon_info = view.findViewById(R.id.pokemon_info);

        }

    }


    @NonNull
    @Override
    public MyPokemonAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.my_pokemon_item_layout, parent, false);
        MyPokemonAdapter.ViewHolder holder = new MyPokemonAdapter.ViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull MyPokemonAdapter.ViewHolder holder, @SuppressLint("RecyclerView") int position) {
        holder.pokemon_img.setImageURL("poke/cp" + myPokemonList.get(position).getImage());
        holder.pokemon_txt.setText(myPokemonList.get(position).getName());
        if (myPokemonList.get(position).getSex() == 0) {
            holder.pokemon_sex.setImageResource(R.mipmap.w);
        } else {
            holder.pokemon_sex.setImageResource(R.mipmap.m);
        }
        if (myPokemonList.get(position).getFlash() == 1) {
            ImageView imageView = new ImageView(context);

            FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT);
            layoutParams.topMargin = 2;
            layoutParams.leftMargin = 80;

            imageView.setLayoutParams(layoutParams);
            imageView.setImageResource(R.mipmap.flash);
            holder.pokemon_info.addView(imageView);
            holder.pokemon_txt.setTextColor(context.getResources().getColor(R.color.black));
        }

        holder.pokemon_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setTitle("提示：");
                builder.setMessage("请选择您的操作");
                builder.setIcon(R.mipmap.ic_launcher_round);
                //点击对话框以外的区域是否让对话框消失
                builder.setCancelable(true);
                //设置正面按钮
                builder.setPositiveButton("出售", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        LayoutInflater factory = LayoutInflater.from(context);
                        View alertDialogView = factory.inflate(R.layout.add_trade_layout, null, false);
                        EditText amount_et = alertDialogView.findViewById(R.id.amount_et);
                        amount_et.setInputType(EditorInfo.TYPE_CLASS_PHONE);
                        Button cancel_btn = alertDialogView.findViewById(R.id.cancel_btn);
                        Button submit_btn = alertDialogView.findViewById(R.id.submit_btn);
                        AlertDialog.Builder editInfoAlertDialog = new AlertDialog.Builder (context);
                        editInfoAlertDialog
                                .setView(alertDialogView)
                                .setCancelable(false)
                                .setTitle("确认上架");

                        addTradeDialog = editInfoAlertDialog.show();

                        cancel_btn.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                addTradeDialog.dismiss();
                            }
                        });

                        submit_btn.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {

                                if (!isNumeric(amount_et.getText().toString()) || amount_et.getText() == null) {
                                    Toast.makeText(context, "请输入有效金额", Toast.LENGTH_SHORT).show();
                                    return;
                                }


                                OkHttp okHttp = new OkHttp();
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        JSONObject jsonObject = new JSONObject();
                                        SharedPreferences mShared = Objects.requireNonNull(context).getSharedPreferences("user", MODE_PRIVATE);
                                        String token = mShared.getString("token", "");
                                        jsonObject.put("token", token);
                                        jsonObject.put("pokemonBaseId", myPokemonList.get(position).getId());
                                        jsonObject.put("amount", amount_et.getText());
                                        try {
                                            JSONObject res = okHttp.Post(context, "trade-list/add", jsonObject);
                                            ((Activity)context).runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    Toast.makeText(context, res.getString("message"), Toast.LENGTH_SHORT).show();
                                                    addTradeDialog.dismiss();
                                                    dialog.dismiss();
                                                }
                                            });
                                        } catch (IOException e) {
                                            throw new RuntimeException(e);
                                        }
                                    }
                                }).start();
                            }
                        });
//                        dialog.dismiss();
                    }
                });
                //设置反面按钮
                builder.setNegativeButton("放生", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        System.out.println("id:"+myPokemonList.get(position).getId());
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                OkHttp okHttp = new OkHttp();
                                JSONObject jsonObject = new JSONObject();
                                SharedPreferences mShared = Objects.requireNonNull(context).getSharedPreferences("user", MODE_PRIVATE);
                                String token = mShared.getString("token", "");
                                jsonObject.put("token", token);
                                jsonObject.put("pokemonBaseId", myPokemonList.get(position).getId());
                                sendMessageBroadcast("free");
                                try {
                                    JSONObject res = okHttp.Post(context, "log-free/freePokemon", jsonObject);
                                } catch (IOException e) {
                                    throw new RuntimeException(e);
                                }
                            }
                        }).start();
                        Toast.makeText(context, "精灵已放生，请重新打开仓库", Toast.LENGTH_SHORT).show();
                        dialog.dismiss();
                    }
                });
                //设置中立按钮
                builder.setNeutralButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                AlertDialog dialog = builder.create();
                //对话框显示的监听事件
                dialog.setOnShowListener(new DialogInterface.OnShowListener() {
                    @Override
                    public void onShow(DialogInterface dialog) {

                    }
                });
                //对话框消失的监听事件
                dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {

                    }
                });
                //显示对话框
                dialog.show();
            }
        });
    }

    @Override
    public int getItemCount() {
        return myPokemonList.size();
    }

    private void sendMessageBroadcast(String message){
        if (!message.isEmpty()){
            Intent intent = new Intent();
            intent.setAction(ACTION_RECEIVE_MESSAGE);
            intent.putExtra(KEY_RECEIVED_DATA, message);
            context.sendBroadcast(intent);
        }
    }


    public static boolean isNumeric(String str){

        Pattern pattern = Pattern.compile("[0-9]*\\.?[0-9]+");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;


    }

}
